package io.github.openUtil.core;

import io.github.openUtil.autoConfig.MinioProperties;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
;import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author openUtil
 */
@Service
public class MinioService {

    private final Logger log;

    private final String defaultBucketName;

    private final MinioClient minioClient;


    public MinioService(MinioProperties properties){
        log = LoggerFactory.getLogger(MinioService.class);
        this.defaultBucketName = properties.getDefaultBucketName();
        this.minioClient = MinioClient.builder().endpoint(properties.getEndpoint()).credentials(properties.getAccessKey(),properties.getSecretKey()).build();
    }

    /**
     * @return 得到client对象
     */
    public MinioClient getMinioClient(){
        return this.minioClient;
    }

    /**
     *
     * @param bucketName 桶名
     * @return 桶是否存在
     */
    public boolean bucketExists(String bucketName) {
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @return 列出所有桶的名字 不带/
     */
    public List<String> listBuckets() {
        List<String> strings = null;
        try {
            strings = minioClient.listBuckets().stream().map(Bucket::name).collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }

    /**
     *
     * @param bucketName 桶名
     * @return 是否构造成功
     */
    public boolean makeBucket(String bucketName) {
        if (!this.bucketExists(bucketName)) {
            try {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * @param bucketName 桶名字
     * @return 存在删除\不存在 均返回 true
     */
    public boolean removeBucket(String bucketName){
        if (!this.bucketExists(bucketName)) {
            try {
                minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * @param bucketName 桶名字
     * @param dir 目录  不要加  /
     * @return 删除目录
     */
    public boolean removeDir(String bucketName, String dir){
        ArrayList<Item> items = this.listObjects(bucketName, dir, true);
        List<String> strings = items.stream().map(Item::objectName).collect(Collectors.toList());
        boolean b = this.removeObjects(bucketName, strings);
        log.info("removeDir: {} {}",bucketName, String.join(" ",strings));
        return b;
    }



    /**
     * @param bucketName 桶名字
     * @param prefix  前缀  直接使用此api查询  如果是目录 需带/  文件不需
     * @param recursive 是否递归子目录
     * @return   查询目录, 列出文件夹。
     */
    public ArrayList<Item> listObjects(String bucketName, String prefix, boolean recursive) {
        ArrayList<Item> items =new ArrayList<>();
        try {
            Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
            if(results.iterator().hasNext()){
                for (Result<Item> next : results) {
                    items.add(next.get());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return items;
        }
        return items;
    }



    /**
     * @param bucketName 桶名
     * @return  获得指定对象前缀的存储桶策略
     */
    public String getBucketPolicy(String bucketName) {
        String config = null;
        try {
           config =  minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket(bucketName).build());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return config;
    }

    /**
     * @param  args 参数  json
     * @return  设置桶策略
     */
    public boolean setBucketPolicy(SetBucketPolicyArgs args){
        try {
            minioClient.setBucketPolicy(args);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }




    /**
     * @param bucketName  桶名  img
     * @param path 目录全路径  支持  avatar/1   avatar/1/
     * @return 结果
     */
    public boolean isDirExist(String bucketName, String path){
       ArrayList<Item> items;
       if(path.charAt(path.length()-1) == '/' ){
           items = this.listObjects(bucketName, path, false);
       }else {
           items = this.listObjects(bucketName, path+ "/", false);
       }
        return items.size() != 0;
    }


    /**
     * @param bucketName  桶名  img
     * @param path 目录全路径  支持  avatar/1   不要加/ 自动帮你加
     * @return 创建目录的结果
     */
    public boolean makeDir(String bucketName, String path){
        if (!this.isDirExist(bucketName,path)) {
            try {
                minioClient.putObject(
                        PutObjectArgs.builder().bucket(bucketName).object(path+"/").stream(
                                new ByteArrayInputStream(new byte[] {}), 0, -1)
                                .build());
                log.info("makeDir: {}/", path);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return  true;
    }


    /**
     * @param bucketName  桶名  img
     * @param path 目录全路径   avatar/1    不支持  avatar/1/  不要加/ 自动帮你加
     * @return 非递归查询目录下 目录和文件 的总数
     */
    public int countDirItems(String bucketName, String path){
        ArrayList<Item> items = this.listObjects(bucketName, path +"/", false);
        return  items.size();
    }

    /**
     * @param bucketName  桶名  img
     * @param path 目录全路径   avatar/1    不支持  avatar/1/  不要加/ 自动帮你加
     * @return 非递归查询目录下 文件 的总数  注意:代码创建的目录总是多1个隐藏文件
     */
    public int countDirFiles(String bucketName, String path){
        ArrayList<Item> items = this.listObjects(bucketName, path +"/", false);
        List<Item> files = items.stream().filter(e -> {
            return !e.isDir();
        }).collect(Collectors.toList());
        return  files.size();
    }

    /**
     * @param bucketName  桶名  img
     * @param path 目录全路径   avatar/1    不支持  avatar/1/  不要加/ 自动帮你加
     * @return 非递归查询目录下 目录 的总数
     */
    public int countDirDirsNum(String bucketName, String path){
        ArrayList<Item> items = this.listObjects(bucketName, path +"/", false);
        List<Item> dirs = items.stream().filter(Item::isDir).collect(Collectors.toList());
        return  dirs.size();
    }

    /**
     * @param bucketName  桶名  img
     * @param path 目录全路径   avatar/1    不支持  avatar/1/  不要加/ 自动帮你加
     * @return 递归查询目录下 所有文件个数
     */
    public int countDirTotals(String bucketName, String path){
        ArrayList<Item> items = this.listObjects(bucketName, path +"/", true);
        return  items.size();
    }



    /**
     * @param bucketName  桶名  img
     * @param path 对象全路径  chunks/lol.jpg
     * @return 结果
     */
    public boolean isFileExist(String bucketName, String path){
        ArrayList<Item> items = this.listObjects(bucketName, path, false);
        if (items.size() >0){
            return !items.get(0).isDir();
        }
        return false;
    }


    /**
     * @param bucketName 桶名
     * @param dstObjectName 合并目标
     * @param subObjectNames 合并子对象
     * @return 返回成功与否
     */
    public boolean composeObject(String bucketName, String dstObjectName,String... subObjectNames) {
        List<ComposeSource> sourceObjectList = new ArrayList<>();
        StringBuilder source = new StringBuilder();
        for (String subObjectName : subObjectNames) {
            sourceObjectList.add(ComposeSource.builder().bucket(bucketName).object(subObjectName).build());
            source.append(" ").append(subObjectName);
        }
        try {
            minioClient.composeObject(ComposeObjectArgs.builder().bucket(bucketName).object(dstObjectName).sources(sourceObjectList).build());
            log.info("merged: {}/{}  from:{}", bucketName, dstObjectName, source);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @param bucketName 桶名
     * @param dstObjectName 合并目标
     * @param subObjectNames 合并子对象
     * @return 返回成功与否
     */
    public boolean composeObject(String bucketName, String dstObjectName, List<String> subObjectNames) {
        List<ComposeSource> sourceObjectList = new ArrayList<>();
        StringBuilder source = new StringBuilder();
        for (String subObjectName : subObjectNames) {
            sourceObjectList.add(ComposeSource.builder().bucket(bucketName).object(subObjectName).build());
            source.append(" ").append(subObjectName);
        }
        try {
            minioClient.composeObject(ComposeObjectArgs.builder().bucket(bucketName).object(dstObjectName).sources(sourceObjectList).build());
            log.info("merged: {}/{}  from:{}", bucketName, dstObjectName, source);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }



    /**
     * @param bucketName 桶名
     * @param dstObjectName 合并目标
     * @param subObjectNames 合并子对象
     * @param  map  用户属性
     * @return 返回成功与否
     */
    public boolean composeObject(String bucketName, String dstObjectName, Map<String,String> map,List<String> subObjectNames) {
        List<ComposeSource> sourceObjectList = new ArrayList<>();
        StringBuilder source = new StringBuilder();
        for (String subObjectName : subObjectNames) {
            sourceObjectList.add(ComposeSource.builder().bucket(bucketName).object(subObjectName).build());
            source.append(" ").append(subObjectName);
        }
        try {
            minioClient.composeObject(ComposeObjectArgs.builder().bucket(bucketName).object(dstObjectName).userMetadata(map).sources(sourceObjectList).build());
            log.info("merged: {}/{}  from:{}", bucketName, dstObjectName, source);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

        /**
         * @param bucketName 桶名
         * @param dstObjectName 合并目标
         * @param subObjectNames 合并子对象
         * @param  map  用户属性
         * @return 返回成功与否
         */
    public boolean composeObject(String bucketName, String dstObjectName, Map<String,String> map, String... subObjectNames) {
        List<ComposeSource> sourceObjectList = new ArrayList<>();
        StringBuilder source = new StringBuilder();
        for (String subObjectName : subObjectNames) {
            sourceObjectList.add(ComposeSource.builder().bucket(bucketName).object(subObjectName).build());
            source.append(" ").append(subObjectName);
        }
        try {
            minioClient.composeObject(ComposeObjectArgs.builder().bucket(bucketName).object(dstObjectName).sources(sourceObjectList).userMetadata(map).build());
            log.info("merged: {}/{}  from:{}", bucketName, dstObjectName, source);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }




    /**
     * @param dstBucket  桶名
     * @param dstObject  赋值目的地
     * @param sourceBucket  源桶名
     * @param sourceObject 源对象
     * @return 复制对象
     */
    public boolean copyObject(String dstBucket, String dstObject ,String sourceBucket, String sourceObject ) {
        try {
            minioClient.copyObject(CopyObjectArgs.builder().bucket(dstBucket).object(dstObject).source(
                    CopySource.builder().bucket(sourceBucket).object(sourceObject).build()
            ).build());
            log.info("dst: {} {} , source: {}  {}" , dstBucket, dstObject, sourceBucket, sourceObject);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * @param bucketName 桶名
     * @param objectName 对象名
     * @return 对象的输入流
     */
    public InputStream getObject(String bucketName, String objectName){
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return inputStream;
    }


    /**
     * 获取对象指定的字节流
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param offset 字节偏移
     * @param length 获取长度
     * @return 获取的输入流
     */
    public InputStream getObjectByOffset(String bucketName, String objectName, Long offset, Long length) {
        InputStream inputStream = null;
        try {
           inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).offset(offset).length(length).build());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return inputStream;
    }


    /**
     * 获取对象指定的字节流
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param offset 字节偏移
     * @return 获取的输入流
     */
    public InputStream getObjectByOffset(String bucketName, String objectName, Long offset) {
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).offset(offset).build());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return inputStream;
    }

    /**
     *
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param fileName 目标文件名
     * @return 下载文件
     */
    public boolean downloadObject(String bucketName, String objectName,  String fileName) {
        try {
             minioClient.downloadObject(DownloadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *
     * @param bucketName  桶名
     * @param objectName  存储的对像名
     * @return 对象的元数据
     */
    public Tags getObjectTags(String bucketName, String objectName) {
        Tags tags = null;
        try {
            tags = minioClient.getObjectTags(GetObjectTagsArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return tags;
    }

    /**
     *
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param reqParams 参数
     * @param method 方法
     * @param expires 过期时间
     * @return 私有也分配
     */
    public String getPresignedObjectUrl(String bucketName, String objectName, Map<String, String> reqParams, Method method, Integer expires){
        String path = null;
        try {
            path = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().
                    bucket(bucketName).object(objectName).extraQueryParams(reqParams).method(method).expiry(expires, TimeUnit.SECONDS).build());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return path;
    }

    /**
     * @param bucketName 桶名
     * @param objectName 对象名
     * @return 生成一个给HTTP GET请求用的presigned URL。浏览器/移动端的客户端可以用这个URL进行下载 过期时间 单位秒   默认7天
     * 即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间，默认值是7天。
     */
    public String getPresignedObjectUrl(String bucketName, String objectName){
        String path = null;
        try {
            path = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().
                    bucket(bucketName).object(objectName).method(Method.GET).expiry(7,TimeUnit.DAYS).build());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return path;
    }





    /**
     *  此方法不会产生覆盖  上传已知流大小
     * @param bucketName  桶名
     * @param objectName  存储的对像名
     * @param inputStream 输入流
     * @param size 大小
     * @param contentType 获取方式
     * @return 是否成功 不带content type为空会报错invalid content type
     */
    public boolean putObject(String bucketName, String objectName, InputStream inputStream, long size, String contentType) {
        try {
            if (!this.bucketExists(bucketName)) {
                this.makeBucket(bucketName);
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
                    .stream(inputStream,size,-1).build());
            log.info("save: {} {}" , bucketName, objectName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 此方法不会产生覆盖
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param inputStream 输入流
     * @param contentType 获取方式
     * @return  带默认type的放入, 不带为空会报错invalid content type
     */
    public boolean putObject(String bucketName, String objectName, InputStream inputStream,  String contentType) {
        try {
            if (!this.bucketExists(bucketName)) {
                this.makeBucket(bucketName);
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
                    .stream(inputStream,-1,10485760).build());
            log.info("save: {} {}" , bucketName, objectName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 此方法覆盖之前的文件
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param inputStream 输入流
     * @param size 文件大小
     * @param contentType type
     * @return  覆盖之前的文件  已知大小流
     */
    public boolean putObjectCover(String bucketName, String objectName, InputStream inputStream, long size, String contentType) {
        try {
            if (!this.bucketExists(bucketName)) {
                this.makeBucket(bucketName);
            }
            if(this.isFileExist(bucketName,objectName)){
                log.info("{}/{} exists , removing ...",bucketName , objectName);
                this.removeObject(bucketName,objectName);
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
                    .stream(inputStream,size,-1).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param inputStream 输入流
     * @param contentType  contentType
     * @return 文件存在覆盖  未知大小流
     */
    public boolean putObjectCover(String bucketName, String objectName, InputStream inputStream, String contentType ) {
        try {
            if (!this.bucketExists(bucketName)) {
                this.makeBucket(bucketName);
            }
            if(this.isFileExist(bucketName,objectName)){
                log.info("{}/{} exists , removing ...",bucketName , objectName);
                this.removeObject(bucketName,objectName);
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
                    .stream(inputStream,-1,10485760).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * @param bucketName 桶名
     * @param objectPathAndName 对象名
     * @param inputStream 输入流
     * @param contentType 获取格式
     * @return   成功与否
     */
    public boolean save(String bucketName, String objectPathAndName, InputStream inputStream, String contentType) {
        try {
            return  this.putObject(bucketName,objectPathAndName,inputStream,inputStream.available(),contentType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }



    /**
     * @param bucketName 桶名
     * @param objectPathAndName 对象名
     * @param inputStream 输入流
     * @return   成功与否
     */
    public boolean save(String bucketName, String objectPathAndName,InputStream inputStream) {
        try {
            return  this.putObject(bucketName,objectPathAndName,inputStream,inputStream.available(),MediaType.BINARY.getContentType());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }



    /**
     * @param objectPathAndName 对象名
     * @param inputStream 输入流
     * @return   成功与否
     */
    public boolean save(String objectPathAndName,InputStream inputStream) {
        return this.save(defaultBucketName,objectPathAndName,inputStream);
    }



    /**
     * @param bucketName 桶名
     * @param objectPathAndName 对象名
     * @param inputStream 输入流
     * @param contentType 获取格式
     * @return   成功与否
     */
    public boolean saveCover(String bucketName, String objectPathAndName, InputStream inputStream, String contentType) {
        try {
            return  this.putObjectCover(bucketName,objectPathAndName,inputStream,inputStream.available(),contentType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * @param bucketName 桶名
     * @param objectPathAndName 对象名
     * @param inputStream 输入流
     * @return   成功与否
     */
    public boolean saveCover(String bucketName, String objectPathAndName, InputStream inputStream) {
        try {
            return  this.putObjectCover(bucketName,objectPathAndName,inputStream,inputStream.available(),MediaType.BINARY.getContentType());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }




    /**
     * @param bucketName 桶名    img
     * @param objectNames 对象名   chunks/1.png
     * @return 移除对象群
     */
    public boolean removeObjects(String bucketName, String... objectNames) {
        List<DeleteObject> objects = new LinkedList<>();
        for (String name : objectNames) {
            objects.add(new DeleteObject(name));
        }
        try {
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objects).build());
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                log.info("deleteInfo: bucketName: {} objectName:{} info:{}",error.bucketName(),error.objectName(),error.message());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * @param bucketName 桶名    img
     * @param objectNames 对象名   chunks/1.png
     * @return 移除对象群
     */
    public boolean removeObjects(String bucketName, List<String> objectNames) {
        List<DeleteObject> objects = new LinkedList<>();
        StringBuilder source = new StringBuilder();
        for (String name : objectNames) {
            objects.add(new DeleteObject(name));
            source.append(" ").append(name);
        }
        try {
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objects).build());
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                log.info("deleteInfo: bucketName: {} objectName:{} info:{}",error.bucketName(),error.objectName(),error.message());
            }
            log.info("delete objects: {} {}",bucketName, source);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * @param bucketName 桶名
     * @param objectName 对象名
     * @return 删除对象
     */
    public boolean removeObject(String bucketName, String  objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            log.info("remove: {} {}",bucketName , objectName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @param bucketName 桶名
     * @param objectName 对象名
     * @param map 参数
     * @return 获取对象tags
     */
    public boolean setObjectTags(String bucketName, String  objectName, Map<String, String> map) {
        try {
            minioClient.setObjectTags(SetObjectTagsArgs.builder().bucket(bucketName).object(objectName).tags(map).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * @param bucketName 桶名
     * @param objectName 对象名
     * @return 获取对象Meta
     */
    public StatObjectResponse getMeta(String bucketName, String  objectName) {

        StatObjectResponse  objectStat = null;
        try {
            objectStat  = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objectStat;
    }


}
